package com.jack.concurrency;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhang_j on 2019/12/6
 * 验证volatile不保证原子性
 */
public class VolatileTest {
    private static final ThreadPoolExecutor EXECUTOR_SERVICE = new ThreadPoolExecutor(100,120,60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadFactoryBuilder().setNameFormat("mycyclicbarrier-pool-%d").build(),
            new ThreadPoolExecutor.CallerRunsPolicy());
    volatile int num = 0;
    public void inc(){
        num++;
    }

//    CompletableFuture future = CompletableFuture.runAsync(()->{
//        for(int j=0;j<100;j++){
//            test.inc();
//        }
//    },EXECUTOR_SERVICE);
//            CompletableFuture.allOf(future).join();
    public static void main(String[] args) {
        final VolatileTest test = new VolatileTest();

        for(int i=0;i<5;i++){
            new Thread(){
                @Override
                public void run() {
                    for(int j=0;j<10;j++)
                        test.inc();
                };
            }.start();
        }

        while(Thread.activeCount()>1)  //保证前面的线程都执行完
            Thread.yield();

        System.out.println(test.num);
    }
}
